package com.test.controller;

import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageInfo;
import com.test.domain.Dept;
import com.test.service.DeptService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class DeptController {
	
	@Resource
	DeptService deptService;
	
	@Resource
	HttpServletRequest request;
	
	/**
	 * 批量删除部门
	 * @param ids 部门数组
	 * @return Map
	 */
	@DeleteMapping("/admin/dept/deletes")
	public @ResponseBody Map<String,Object> deletes(@RequestBody Integer[] ids){
		Map<String,Object> data=new HashMap<>();
		int result = deptService.deletes(ids);
		if(result!=ids.length){
			data.put("flag", false);
			data.put("msg","操作失败");
		}else {
			data.put("flag", true);
			data.put("msg","操作成功");
		}
		return data;
	}
	
	/**
	 * 后台-部门管理
	 * @return
	 */
	@GetMapping("/admin/dept")
	public String deptPage(){
		return "dept";
	}
	
	/**
	 * 显示部门列表数据
	 * @return PageInfo
	 */
	@RequestMapping("/admin/dept/list")
	public @ResponseBody PageInfo<Dept> deptListPage(Dept dept){
		PageInfo<Dept> pageInfo=deptService.selectForPageInfo(dept);
		return pageInfo;
	}
	
	@RequestMapping("/app/dept/list")
	public @ResponseBody JSONObject selectDeptList(Dept dept){
		PageInfo<Dept> pageInfo=deptService.selectForPageInfo(dept);
		JSONObject data=new JSONObject();
		data.put("list", pageInfo.getList());
		data.put("loadMoreStatus", pageInfo.isHasNextPage()?"more":"noMore");
		return data;
	}
	
	/**
	 * 新增或者修改部门
	 * @param dept 部门对象
	 * @return Map
	 */
	@PostMapping("/admin/dept/addOrUpdate")
	public @ResponseBody Map<String,Object> addOrUpdate(@RequestBody Dept dept){
		Map<String,Object> data=new HashMap<>();
		int result=0;
		System.out.println(dept);
		if(dept!=null && dept.getId()!=null){
			result = deptService.update(dept);
		}else{
			result = deptService.add(dept);
		}
		if(result==0){
			data.put("flag", false);
			data.put("msg","操作失败");
		}else {
			data.put("flag", true);
			data.put("msg","操作成功");
		}
		return data;
	}
	
	/**
	 * 删除单个部门数据
	 * @param id 部门ID
	 * @return Map
	 */
	@DeleteMapping ("/admin/dept/delete")
	public @ResponseBody Map<String,Object> delete(Integer id){
		System.out.println("id="+id);
		Map<String,Object> data=new HashMap<>();
		int result = deptService.delete(id);
		if(result==0){
			data.put("flag", false);
			data.put("msg","操作失败");
		}else {
			data.put("flag", true);
			data.put("msg","操作成功");
		}
		return data;
	}
	
}